package com.itheima.kafka.simple;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.time.Duration;
import java.util.Collections;
import java.util.Properties;

/**
 * @Description:
 * @Version: V1.0
 */
public class ConsumerFastStart {
    public static final String TOPIC = "itcast-heima";

    public static void main(String[] args) {
        // 创建 kafka 配置对象
        Properties properties = new Properties();

        // 参数封装**
//        properties.put("bootstrap.servers", "192.168.200.129:9092");
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.200.129:9092");
        // key 序列化对象StringSerializer
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
        // value 序列化 StringSerializer
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");

        // *** 配置消费组
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "group2");


        // 创建KafkaConsumer
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties);

        // 订阅消息
        consumer.subscribe(Collections.singleton(TOPIC));


        while (true) {

//            try {
//                Thread.sleep(2000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }

            ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(1000));

            for (ConsumerRecord<String, String>  record : records) {
                // 监听到消息
                System.out.println(record.key());
                System.out.println(record.value());

            }
        }




    }
}
